<?php

namespace App\Model;

use App\User;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;

class Bill extends BaseModel
{
    use HasFactory, SoftDeletes;

    public $table = 'bill';

    public $guarded = [];

    public $appends = ['is_fail', 'fail_days'];

    public function contract()
    {
        return $this->belongsTo(Contract::class);
    }

    public function house()
    {
        return $this->belongsTo(House::class);
    }

    public function business()
    {
        return $this->belongsTo(Business::class);
    }

    public function tenant()
    {
        return $this->belongsTo(Tenant::class);
    }

    public function getIsFailAttribute()
    {
        if ($this->is_paid) {
            return 0;
        }
        if (!$this->pay_date) {
            return 0;
        }
        if ($this->pay_date < now()->toDateString()) {
            return 1;
        }
        return 0;
    }

    public function getFailDaysAttribute()
    {
        if (!$this->pay_date) {
            return 0;
        }
        if ($this->pay_date && $this->pay_date < now()->toDateString()) {
            return Carbon::now()->diffInDays(Carbon::createFromFormat('Y-m-d', $this->pay_date));
        }
        return 0;
    }

    public function billPay()
    {
        return $this->hasOne(BillPay::class);
    }

    public function user()
    {
        return $this->hasOne(User::class, 'mobile', 'mobile');
    }

    public function device()
    {
        return $this->belongsTo(Device::class);
    }
}
